import { loginApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import router from '@/router'

const state = {
  token: getToken() || ''
}

const mutations = {
  setToken: (state, token) => {
    state.token = token
    setToken(token)
  },
   removeToken(state) {
     removeToken()
     state.token = ''
  }

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginApi(userInfo)
        .then((response) => {
          const data = response
          commit('setToken', data.token)
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 退出的action
  logout({ commit, state }) {
    // 删除token
    commit('removeToken')
    commit('settings/resetTheme', null, { root: true })
    state.token = ''
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
